<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="text" />

    <script>
      function mydebounce(fn, wait) {
        let timer = null;
        return function (...args) {
          if (timer) {
            clearTimeout(timer);
            timer = null;
          }
          timer = setTimeout(() => {
            fn.apply(this, args);
          }, wait);
        };
      }

      // -------------------
      function myThrottle(fn, wait) {
        let timer = null;
        return function (...args) {
          if (!timer) {
            timer = setTimeout(() => {
              fn.apply(this, args);
              timer = null;
            }, wait);
          }
        };
      }

      const inputEl = document.querySelector("input");

      let counter = 1;
      function searchChange() {
        console.log(`第${counter++}次网络请求`, this.value);
      }

      // 使用自己封装的函数实现防抖
      // inputEl.oninput = mydebounce(searchChange, 3000);
      inputEl.oninput = myThrottle(searchChange, 500);
    </script>
  </body>
</html>
